//
//  TT_OSSManager.m
//  ZKGX
//
//  Created by 王洋 on 2020/3/12.
//  Copyright © 2020 王洋. All rights reserved.
//

#import "AFNetworking.h"
#import "TT_OSSManager.h"
#import "SDWebImageManager.h"

#import "UIImage+FixOrientation.h"
//#import <AliyunOSSiOS/OSSService.h>

@interface TT_OSSManager ()<TZImagePickerControllerDelegate>

@end

@implementation TT_OSSManager

+ (instancetype)manager {
    static TT_OSSManager * manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [TT_OSSManager new];

    });
    return manager;
}

+ (NSString *)resizeSourceUrl:(NSString *)url width:(CGFloat)width {
    
    NSString *imgUrl = @"";
    if ([url containsString:@"?"]) {
        NSArray *array = [url componentsSeparatedByString:@"?"]; //从字符A中分隔成2个元素的数组
        if (array.count > 0) {
            imgUrl = array.firstObject;
        }
    } else {
        imgUrl = url;
    }
    imgUrl = [NSString stringWithFormat:@"%@%@",imgUrl,[NSString stringWithFormat:@"?x-oss-process=image/resize,h_%.0f",width]];
    url = imgUrl;
    return url;
}

+ (NSString *)reformWebPUrl:(NSString *)url{
    
    NSString *imgUrl = @"";
    if ([url containsString:@"?"]) {
        NSArray *array = [url componentsSeparatedByString:@"?"]; //从字符A中分隔成2个元素的数组
        if (array.count > 0) {
            imgUrl = array.firstObject;
        }
    } else {
        imgUrl = url;
    }
    imgUrl = [NSString stringWithFormat:@"%@%@",imgUrl,@"?x-oss-process=image/format,webp"];
    url = imgUrl;
    return url;
}

+ (NSString *)reSourceUrl:(NSString *)url type:(BA_resizeType)type {
    switch (type) {
        case BA_resizeType_none:{
            return [TT_OSSManager clearSourceUrl:url];
        } break;
        case BA_resizeType_max:{
            return [TT_OSSManager resizeSourceUrl:url width:1200];
        } break;
        case BA_resizeType_pro:{
            return [TT_OSSManager resizeSourceUrl:url width:500];
        } break;
        case BA_resizeType_plus:{
            return [TT_OSSManager resizeSourceUrl:url width:300];
        } break;
        case BA_resizeType_small:{
            return [TT_OSSManager resizeSourceUrl:url width:100];
        } break;
        case BA_resizeType_webP:{
            return [TT_OSSManager reformWebPUrl:url];
        } break;
            
        default:{
            return url;
        } break;
    }
}

+ (NSString *)clearSourceUrl:(NSString *)url {
    
    NSString *imgUrl = @"";
    if ([url containsString:@"?"]) {
        NSArray *array = [url componentsSeparatedByString:@"?"]; //从字符A中分隔成2个元素的数组
        if (array.count > 0) {
            imgUrl = array.firstObject;
        }
    } else {
        imgUrl = url;
    }
    url = imgUrl;
    return url;
}

+ (void)cacheSourceUrl:(NSString *)url {
    [[SDWebImageManager sharedManager] loadImageWithURL:[NSURL URLWithString:url] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
            
        } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
            
        }];
}

+ (NSString *)deviceAutoPic:(NSString *)url {

    NSString *resultUrl = @"";
    
        NSInteger height = TTScreenHeight;
        NSString *midStr = @"";
        switch (height) {
            case 480:
                midStr = @"_x1";
                break;
            case 568:
                midStr = @"_x2";
                break;
            case 667:
                midStr = @"_x3";
                break;
            case 736:
                midStr = @"_x4";
                break;
            case 812:
                midStr = @"_x5";
                break;
            case 896:
                midStr = @"_x6";
                break;
            default:
                midStr = @"_x6";
                break;
        }
        NSString *subString = [url substringToIndex:url.length - 4];
        NSString *endString = [url substringFromIndex:url.length - 4];
        NSString *tempStr = [NSString stringWithFormat:@"%@%@%@",subString,midStr,endString];
    
    resultUrl = [tempStr copy];
    

    return resultUrl;;
}


+ (NSString *)uuidString {
    CFUUIDRef uuid_ref = CFUUIDCreate(NULL);
    CFStringRef uuid_string_ref= CFUUIDCreateString(NULL, uuid_ref);
    NSString *uuid = [NSString stringWithString:(__bridge NSString *)uuid_string_ref];
    CFRelease(uuid_ref);
    CFRelease(uuid_string_ref);
    return [uuid lowercaseString];
}

- (void)selectPhotoFromVC:(UIViewController *)vc photoCount:(NSInteger)count AndUploadServerComption:(void (^)(NSArray *urlArray))comption {

    TZImagePickerController *pickerVC = [[TZImagePickerController alloc]
                                   initWithMaxImagesCount:count delegate:self];

    pickerVC.naviBgColor = default_color_white;
    pickerVC.naviTitleColor = default_color_black;
    pickerVC.barItemTextColor = default_color_black;

    pickerVC.photoWidth = 2048.0f;
    
    pickerVC.preferredLanguage = @"zh-Hans";

    //筛选到只剩图片
    pickerVC.allowPickingVideo = NO;
    pickerVC.allowPickingMultipleVideo = NO;
    pickerVC.allowPickingGif = NO;
    pickerVC.allowPickingVideo = NO;

    pickerVC.showSelectedIndex = YES;
    pickerVC.showSelectBtn = YES;

    //裁剪
    pickerVC.allowCrop = YES;
    pickerVC.cropRect = CGRectMake( 0 ,(TTScreenHeight - TTScreenWidth)/2, TTScreenWidth, TTScreenWidth);

    WEAKSELF
    [pickerVC setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        
        // 准备保存结果的数组，元素个数与上传的图片个数相同，先用 NSNull 占位
        NSMutableArray* result = [NSMutableArray array];
        for (int i = 0; i < photos.count; i++) {
            [result addObject:[NSNull null]];
        }
        
        dispatch_group_t group = dispatch_group_create();

        [SVProgressHUD showWithStatus:@"正在上传评价图片"];
        for (NSInteger i = 0; i < photos.count; i++)
        {
            dispatch_group_enter(group);
            dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                
                // ContentType设置
                AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
                manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"image/jpeg",@"image/png",@"application/octet-stream",@"text/json",nil];
                manager.requestSerializer= [AFHTTPRequestSerializer serializer];
                manager.responseSerializer= [AFHTTPResponseSerializer serializer];
                [manager.requestSerializer setValue:[TTUserModel sharedObject].token forHTTPHeaderField:@"token"];
                
                // 上传完整地址
                NSString * urlString = [NSString stringWithFormat:@"%@headImgUpload",TT_Global_Service_Domain];
                
                [manager POST:urlString parameters:nil headers:@{} constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
                            
                    if (photos[i] != nil) {
                    NSData *data = UIImageJPEGRepresentation(photos[i], 0.2f);
                    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                    formatter.dateFormat = @"yyyyMMddHHmmss";
                    NSString *str = [formatter stringFromDate:[NSDate date]];
                    NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
                    [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/jpg"];
                    }
                    
                } progress:^(NSProgress * _Nonnull uploadProgress) {
                    NSLog(@"%.2f",uploadProgress.fractionCompleted);

                } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

                    NSString *resultStr = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];

                    if ([resultStr isKindOfClass:[NSString class]]) {
                        
                        @synchronized (result) {
                            result[i] = resultStr;
                        }
                    }
                    dispatch_group_leave(group);
                    
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    dispatch_group_leave(group);

                }];
            });
           
        }
        
        dispatch_group_notify(group, dispatch_get_main_queue(), ^{
            NSLog(@"上传完成!");
            
            comption(result);
            [SVProgressHUD showSuccessWithStatus:@"上传成功"];
            [SVProgressHUD dismissWithDelay:0.5];

//            weakSelf.submitArray[section].imageUrls = @[].mutableCopy;
//            for (int i = 0; i < result.count; i++) {
//                NSString *imgStr = result[i];
//
//                if ([imgStr isKindOfClass:[NSString class]]) {
//                    
//                    CommonMediaModel *model = [[CommonMediaModel alloc] init];
//                    model.url = imgStr;
//                    [weakSelf.submitArray[section].imageUrls addObject:model];
//                    [weakSelf.tableview reloadData];
//                }
//            }
        });
    }];

    pickerVC.modalPresentationStyle = UIModalPresentationFullScreen;
    [vc presentViewController:pickerVC animated:YES completion:nil];
    
}

@end
